//
// Created by sherlock on 2021/3/14.
//
#include <iostream>
#include <unistd.h>

using namespace std;

pthread_cond_t qready = PTHREAD_COND_INITIALIZER;//初始构造条件变量
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;//初始构造锁

int x = 10, y = 20;

void *func1(void *arg) {
  cout << "func1" << endl;
  pthread_mutex_lock(&qlock);
  while (x < y) {
    pthread_cond_wait(&qready, &qlock);
  }
  pthread_mutex_unlock(&qlock);
  cout << "func1 end" << endl;
}

void *func2(void *arg) {
  cout << "func2" << endl;
  pthread_mutex_lock(&qlock);
  x = 20, y = 10;
  cout << "x & y changed" << endl;
  pthread_mutex_unlock(&qlock);
  if (x > y) {
    pthread_cond_signal(&qready);
  }
  cout << "func2 end" << endl;
}

int main() {
  pthread_t tid1, tid2;
  int res = pthread_create(&tid1, nullptr, func1, nullptr);
  if (res) {
    cout << "pthread 1 create error" << endl;
    return res;
  }
  sleep(2);
  res = pthread_create(&tid2, nullptr, func2, nullptr);
  if (res) {
    cout << "pthread 2 create error" << endl;
    return res;
  }
  sleep(10);
  return 0;
}
